package com.manli.common.utils;

import com.alibaba.fastjson.JSONObject;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class HttpUtil {

    public static String X_WWW_FORM_URLENCODED = "application/x-www-form-urlencoded";
    public static String JSON = "application/json";

    public static String httpGet(String getUrl) throws Exception{
        HttpURLConnection httpURLConnection = null;
        try {
            // 1. 得到访问地址的URL
            URL url = new URL(getUrl);
            // 2. 得到网络访问对象java.net.HttpURLConnection
            httpURLConnection = (HttpURLConnection) url.openConnection();
            /* 3. 设置请求参数（过期时间，输入、输出流、访问方式），以流的形式进行连接 */
            // 设置是否向HttpURLConnection输出
            httpURLConnection.setDoOutput(false);
            // 设置是否从httpUrlConnection读入
            httpURLConnection.setDoInput(true);
            // 设置请求方式　默认为GET
            httpURLConnection.setRequestMethod("GET");
            // 设置是否使用缓存
            httpURLConnection.setUseCaches(false);
            // 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向
            httpURLConnection.setInstanceFollowRedirects(true);
            // 设置连接超时时间
            httpURLConnection.setConnectTimeout(3000);
            // 设置读取返回超时时间
            httpURLConnection.setReadTimeout(3000);
            // 连接
            httpURLConnection.connect();
            // 4. 得到响应状态码的返回值 responseCode
            int code = httpURLConnection.getResponseCode();
            // 5. 如果返回值正常，数据在网络中是以流的形式得到服务端返回的数据
            String msg = "";
            if (code == 200) { // 正常响应
                log.info("正常响应200码：" +  msg);
                // 从流中读取响应信息
                BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                String line = null;
                while ((line = reader.readLine()) != null) { // 循环从流中读取
                    msg += line;
                }
                reader.close(); // 关闭流
                // 显示响应结果
                log.info("请求返回：" +  msg);
                return msg;
            }else{
                // 显示响应结果
                log.info("异常响应码" + code + "：" +  msg);
                // 从流中读取响应信息
                BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream()));
                String line = null;
                while ((line = reader.readLine()) != null) { // 循环从流中读取
                    msg += line;
                }
                reader.close(); // 关闭流
                // 显示响应结果
                log.info("请求返回：" +  msg);
                return null;
            }
        } catch (Exception e) {
            log.error("请求出错，错误信息："+e.getMessage()+";");
            e.printStackTrace();
            throw e;
        }finally {
            // 6. 断开连接，释放资源
            if (null != httpURLConnection){
                try {
                    httpURLConnection.disconnect();
                }catch (Exception e){
                    log.info("httpURLConnection 流关闭异常："+ e.getLocalizedMessage());
                    e.printStackTrace();
                    throw e;
                }
            }
        }
    }

    public static String httpsGet(String getUrl) throws Exception{
        HttpsURLConnection httpURLConnection = null;
        try {
            // 1. 得到访问地址的URL
            URL url = new URL(getUrl);
            // 2. 得到网络访问对象java.net.HttpURLConnection
            httpURLConnection = (HttpsURLConnection) url.openConnection();
            /* 3. 设置请求参数（过期时间，输入、输出流、访问方式），以流的形式进行连接 */
            // 设置是否向HttpURLConnection输出
            httpURLConnection.setDoOutput(false);
            // 设置是否从httpUrlConnection读入
            httpURLConnection.setDoInput(true);
            // 设置请求方式　默认为GET
            httpURLConnection.setRequestMethod("GET");
            // 设置是否使用缓存
            httpURLConnection.setUseCaches(false);
            // 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向
            httpURLConnection.setInstanceFollowRedirects(true);
            // 设置连接超时时间
            httpURLConnection.setConnectTimeout(3000);
            // 设置读取返回超时时间
            httpURLConnection.setReadTimeout(3000);
            // 连接
            httpURLConnection.connect();
            // 4. 得到响应状态码的返回值 responseCode
            int code = httpURLConnection.getResponseCode();
            // 5. 如果返回值正常，数据在网络中是以流的形式得到服务端返回的数据
            String msg = "";
            if (code == 200) { // 正常响应
                log.info("正常响应200码：" +  msg);
                // 从流中读取响应信息
                BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                String line = null;
                while ((line = reader.readLine()) != null) { // 循环从流中读取
                    msg += line;
                }
                reader.close(); // 关闭流
                // 显示响应结果
                log.info("请求返回：" +  msg);
                return msg;
            }else{
                // 显示响应结果
                log.info("异常响应码" + code + "：" +  msg);
                // 从流中读取响应信息
                BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream()));
                String line = null;
                while ((line = reader.readLine()) != null) { // 循环从流中读取
                    msg += line;
                }
                reader.close(); // 关闭流
                // 显示响应结果
                log.info("请求返回：" +  msg);
                return null;
            }
        } catch (Exception e) {
            log.error("请求出错，错误信息："+e.getMessage()+";");
            e.printStackTrace();
            throw e;
        }finally {
            // 6. 断开连接，释放资源
            if (null != httpURLConnection){
                try {
                    httpURLConnection.disconnect();
                }catch (Exception e){
                    log.info("httpURLConnection 流关闭异常："+ e.getLocalizedMessage());
                    e.printStackTrace();
                    throw e;
                }
            }
        }
    }

    public static File httpsGetImagAsFile(String getUrl) throws Exception{
        HttpsURLConnection httpURLConnection = null;
        try {
            // 1. 得到访问地址的URL
            URL url = new URL(getUrl);
            // 2. 得到网络访问对象java.net.HttpURLConnection
            httpURLConnection = (HttpsURLConnection) url.openConnection();
            /* 3. 设置请求参数（过期时间，输入、输出流、访问方式），以流的形式进行连接 */
            // 设置是否向HttpURLConnection输出
            httpURLConnection.setDoOutput(false);
            // 设置是否从httpUrlConnection读入
            httpURLConnection.setDoInput(true);
            // 设置请求方式　默认为GET
            httpURLConnection.setRequestMethod("GET");
            // 设置是否使用缓存
            httpURLConnection.setUseCaches(false);
            // 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向
            httpURLConnection.setInstanceFollowRedirects(true);
            // 设置连接超时时间
            httpURLConnection.setConnectTimeout(3000);
            // 设置读取返回超时时间
            httpURLConnection.setReadTimeout(3000);
            // 连接
            httpURLConnection.connect();
            // 4. 得到响应状态码的返回值 responseCode
            int code = httpURLConnection.getResponseCode();
            // 5. 如果返回值正常，数据在网络中是以流的形式得到服务端返回的数据
            String msg = "";
            if (code == 200) { // 正常响应
                log.info("正常响应200码：" +  msg);
                // 从流中读取响应信息
                File file = File.createTempFile(new Date().getTime() + "", ".png");
                OutputStream os = new FileOutputStream(file);

                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                while ((bytesRead = httpURLConnection.getInputStream().read(buffer, 0, 8192)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }

                httpURLConnection.getInputStream().close();
                os.close();
                // 显示响应结果
                log.info("请求返回：" +  msg);
                return file;
            }else{
                // 显示响应结果
                log.info("异常响应码" + code + "：" +  msg);
                // 从流中读取响应信息
                BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream()));
                String line = null;
                while ((line = reader.readLine()) != null) { // 循环从流中读取
                    msg += line;
                }
                reader.close(); // 关闭流
                // 显示响应结果
                log.info("请求返回：" +  msg);
                return null;
            }
        } catch (Exception e) {
            log.error("请求出错，错误信息："+e.getMessage()+";");
            e.printStackTrace();
            throw e;
        }finally {
            // 6. 断开连接，释放资源
            if (null != httpURLConnection){
                try {
                    httpURLConnection.disconnect();
                }catch (Exception e){
                    log.info("httpURLConnection 流关闭异常："+ e.getLocalizedMessage());
                    e.printStackTrace();
                    throw e;
                }
            }
        }
    }

    /**
     * 访问阿里图片专用
     * @param getUrl
     * @return
     * @throws Exception
     */
    public static Map httpsGetImg(String getUrl) throws Exception{
        HttpsURLConnection httpURLConnection = null;
        try {
            // 1. 得到访问地址的URL
            URL url = new URL(getUrl);
            // 2. 得到网络访问对象java.net.HttpURLConnection
            httpURLConnection = (HttpsURLConnection) url.openConnection();
            httpURLConnection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36 Edg/83.0.478.44");
            httpURLConnection.setRequestProperty("sec-fetch-site", "cross-site");
            httpURLConnection.setRequestProperty("sec-fetch-mode", "no-cors");
            httpURLConnection.setRequestProperty("sec-fetch-dest", "image");
            httpURLConnection.setRequestProperty("authority", "img.alicdn.com");
            httpURLConnection.setRequestProperty("scheme", "https");
            httpURLConnection.setRequestProperty("accept", "image/webp,image/apng,image/*,*/*;q=0.8");
            httpURLConnection.setRequestProperty("accept-encoding", "gzip, deflate, br");
            httpURLConnection.setRequestProperty("accept-language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
            /* 3. 设置请求参数（过期时间，输入、输出流、访问方式），以流的形式进行连接 */
            // 设置是否向HttpURLConnection输出
            httpURLConnection.setDoOutput(false);
            // 设置是否从httpUrlConnection读入
            httpURLConnection.setDoInput(true);
            // 设置请求方式　默认为GET
            httpURLConnection.setRequestMethod("GET");
            // 设置是否使用缓存
            httpURLConnection.setUseCaches(false);
            // 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向
            httpURLConnection.setInstanceFollowRedirects(true);
            // 设置连接超时时间
            httpURLConnection.setConnectTimeout(3000);
            // 设置读取返回超时时间
            httpURLConnection.setReadTimeout(30000);
            // 连接
            httpURLConnection.connect();
            // 4. 得到响应状态码的返回值 responseCode
            int code = httpURLConnection.getResponseCode();
            String type = httpURLConnection.getHeaderField("content-type");
            String fileSize = httpURLConnection.getHeaderField("content-length");
            // 5. 如果返回值正常，数据在网络中是以流的形式得到服务端返回的数据
            String msg = "";
            if (code == 200) { // 正常响应
                log.info("正常响应200码：" +  msg);
                // 从流中读取响应信息
                byte[] buffer = new byte[1024];
                int length = 0;

                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                while ((length = httpURLConnection.getInputStream().read(buffer)) > 0) {
                    byteArrayOutputStream.write(buffer, 0, length);
                }
                byte[] imgBytes = byteArrayOutputStream.toByteArray();

                Map map = new HashMap();
                map.put("in",new ByteArrayInputStream(imgBytes));
                map.put("type",type);
                map.put("fileSize",fileSize);
//                return new ByteArrayInputStream(imgBytes);
                return map;

            }else{
                // 显示响应结果
                log.info("异常响应码" + code + "：" +  msg);
                // 从流中读取响应信息
                BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream()));
                String line = null;
                while ((line = reader.readLine()) != null) { // 循环从流中读取
                    msg += line;
                }
                reader.close(); // 关闭流
                // 显示响应结果
                log.info("请求返回：" +  msg);
                return null;
            }
        } catch (Exception e) {
            log.error("请求出错，错误信息："+e.getMessage()+";");
            e.printStackTrace();
            throw e;
        }finally {
            // 6. 断开连接，释放资源
            if (null != httpURLConnection){
                try {
                    httpURLConnection.disconnect();
                }catch (Exception e){
                    log.info("httpURLConnection 流关闭异常："+ e.getLocalizedMessage());
                    e.printStackTrace();
                    throw e;
                }
            }
        }
    }

    public static String httpPost(String getUrl, Map<String,String> params) throws Exception{
        HttpURLConnection httpURLConnection = null;
        try {
            // 1. 得到访问地址的URL
            URL url = new URL(getUrl);
            // 2. 得到网络访问对象java.net.HttpURLConnection
            httpURLConnection = (HttpURLConnection) url.openConnection();
            /* 3. 设置请求参数（过期时间，输入、输出流、访问方式），以流的形式进行连接 */
            // 设置是否向HttpURLConnection输出
            httpURLConnection.setDoOutput(true);
            // 设置是否从httpUrlConnection读入
            httpURLConnection.setDoInput(true);
            // 设置请求方式　默认为GET
            httpURLConnection.setRequestMethod("POST");
            // 设置使用标准编码格式编码参数的名-值对
            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 设置请求头,待选
            //httpURLConnection.addRequestProperty("token","");
            // 设置是否使用缓存
            httpURLConnection.setUseCaches(false);
            // 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向
            httpURLConnection.setInstanceFollowRedirects(true);
            // 设置连接超时时间
            httpURLConnection.setConnectTimeout(6000);
            // 设置读取返回超时时间
            httpURLConnection.setReadTimeout(6000);
            // 连接
            httpURLConnection.connect();

            String paramsStr = "";
            for(Map.Entry<String, String> entry : params.entrySet()){
                if(entry.getValue() == null){
                    continue;
                }
                paramsStr += entry.getKey() + "=" + entry.getValue() + "&";
            }
            paramsStr = paramsStr.substring(0,paramsStr.length() - 1);
            log.info("请求数据为：" +  paramsStr);

            OutputStream out = httpURLConnection.getOutputStream();
            out.write(paramsStr.getBytes());
            out.flush();
            out.close();
            // 4. 得到响应状态码的返回值 responseCode
            int code = httpURLConnection.getResponseCode();
            // 5. 如果返回值正常，数据在网络中是以流的形式得到服务端返回的数据
            String msg = "";
            if (code == 200) { // 正常响应
                log.info("正常响应200码：" +  msg);
                // 从流中读取响应信息
                BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                String line = null;
                while ((line = reader.readLine()) != null) { // 循环从流中读取
                    msg += line;
                }
                reader.close(); // 关闭流
                // 显示响应结果
                log.info("请求返回：" +  msg);
                return msg;
            }else{
                // 显示响应结果
                log.info("异常响应码" + code + "：" +  msg);
                // 从流中读取响应信息
                BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream()));
                String line = null;
                while ((line = reader.readLine()) != null) { // 循环从流中读取
                    msg += line;
                }
                reader.close(); // 关闭流
                // 显示响应结果
                log.info("请求返回：" +  msg);
                return null;
            }
        } catch (Exception e) {
            log.error("请求出错，错误信息："+e.getMessage()+";");
            e.printStackTrace();
            throw e;
        }finally {
            // 6. 断开连接，释放资源
            if (null != httpURLConnection){
                try {
                    httpURLConnection.disconnect();
                }catch (Exception e){
                    log.info("httpURLConnection 流关闭异常："+ e.getLocalizedMessage());
                    e.printStackTrace();
                    throw e;
                }
            }
        }
    }


    public static String httpsPost(String getUrl, Map<String,String> params) throws Exception{
        HttpsURLConnection httpURLConnection = null;
        try {
            // 1. 得到访问地址的URL
            URL url = new URL(getUrl);
            // 2. 得到网络访问对象java.net.HttpURLConnection
            httpURLConnection = (HttpsURLConnection) url.openConnection();
            /* 3. 设置请求参数（过期时间，输入、输出流、访问方式），以流的形式进行连接 */
            // 设置是否向HttpURLConnection输出
            httpURLConnection.setDoOutput(true);
            // 设置是否从httpUrlConnection读入
            httpURLConnection.setDoInput(true);
            // 设置请求方式　默认为GET
            httpURLConnection.setRequestMethod("POST");
            // 设置使用标准编码格式编码参数的名-值对
            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 设置请求头,待选
            //httpURLConnection.addRequestProperty("token","");
            // 设置是否使用缓存
            httpURLConnection.setUseCaches(false);
            // 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向
            httpURLConnection.setInstanceFollowRedirects(true);
            // 设置连接超时时间
            httpURLConnection.setConnectTimeout(3000);
            // 设置读取返回超时时间
            httpURLConnection.setReadTimeout(3000);
            // 连接
            httpURLConnection.connect();

            String paramsStr = "";
            for(Map.Entry<String, String> entry : params.entrySet()){
                paramsStr += entry.getKey() + "=" + entry.getValue() + "&";
            }
            paramsStr = paramsStr.substring(0,paramsStr.length() - 1);
            log.info("请求数据为：" +  paramsStr);

            OutputStream out = httpURLConnection.getOutputStream();
            out.write(paramsStr.getBytes());
            out.flush();
            out.close();
            // 4. 得到响应状态码的返回值 responseCode
            int code = httpURLConnection.getResponseCode();
            // 5. 如果返回值正常，数据在网络中是以流的形式得到服务端返回的数据
            String msg = "";
            if (code == 200) { // 正常响应
                log.info("正常响应200码：" +  msg);
                // 从流中读取响应信息
                BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                String line = null;
                while ((line = reader.readLine()) != null) { // 循环从流中读取
                    msg += line;
                }
                reader.close(); // 关闭流
                // 显示响应结果
                log.info("请求返回：" +  msg);
                return msg;
            }else{
                // 显示响应结果
                log.info("异常响应码" + code + "：" +  msg);
                // 从流中读取响应信息
                BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream()));
                String line = null;
                while ((line = reader.readLine()) != null) { // 循环从流中读取
                    msg += line;
                }
                reader.close(); // 关闭流
                // 显示响应结果
                log.info("请求返回：" +  msg);
                return null;
            }
        } catch (Exception e) {
            log.error("请求出错，错误信息："+e.getMessage()+";");
            e.printStackTrace();
            throw e;
        }finally {
            // 6. 断开连接，释放资源
            if (null != httpURLConnection){
                try {
                    httpURLConnection.disconnect();
                }catch (Exception e){
                    log.info("httpURLConnection 流关闭异常："+ e.getLocalizedMessage());
                    e.printStackTrace();
                    throw e;
                }
            }
        }
    }

    public static String httpsPostImg(String getUrl, File file,String key) throws Exception{
        String endString = "\r\n";
        String twoHyphen = "--";
        String boundary = "*****";

        HttpsURLConnection httpURLConnection = null;
        try {
            // 1. 得到访问地址的URL
            URL url = new URL(getUrl);
            // 2. 得到网络访问对象java.net.HttpURLConnection
            httpURLConnection = (HttpsURLConnection) url.openConnection();
            /* 3. 设置请求参数（过期时间，输入、输出流、访问方式），以流的形式进行连接 */
            // 设置是否向HttpURLConnection输出
            httpURLConnection.setDoOutput(true);
            // 设置是否从httpUrlConnection读入
            httpURLConnection.setDoInput(true);
            // 设置请求方式　默认为GET
            httpURLConnection.setRequestMethod("POST");
            // 设置使用标准编码格式编码参数的名-值对
            httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" +boundary);
            // 设置请求头,待选
            //httpURLConnection.addRequestProperty("token","");
            // 设置是否使用缓存
            httpURLConnection.setUseCaches(false);
            // 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向
            httpURLConnection.setInstanceFollowRedirects(true);
            // 设置连接超时时间
            httpURLConnection.setConnectTimeout(3000);
            // 设置读取返回超时时间
            httpURLConnection.setReadTimeout(3000);
            // 连接
            httpURLConnection.connect();

            OutputStream out = httpURLConnection.getOutputStream();

            //设置DataOutputStream
            DataOutputStream dsDataOutputStream = new DataOutputStream(out);
            dsDataOutputStream.writeBytes(twoHyphen + boundary + endString);
            dsDataOutputStream.writeBytes("Content-Disposition:form-data;" + "name=\"" + key + "\";filename=\"" + file.getName() + "\"" + endString);
            dsDataOutputStream.writeBytes(endString);

            //暂定2M，微信上传最大为1M
            int bufferSize = 1048576 * 2;
            byte[] buffer = new byte[bufferSize];
            int length = -1;
            FileInputStream inputStream = new FileInputStream(file);
            while ((length = inputStream.read(buffer)) != -1) {
                dsDataOutputStream.write(buffer, 0, length);
            }

            dsDataOutputStream.writeBytes(endString);
            dsDataOutputStream.writeBytes(twoHyphen + boundary + twoHyphen + endString);

            inputStream.close();
            dsDataOutputStream.flush();
            dsDataOutputStream.close();
            out.flush();
            out.close();
            // 4. 得到响应状态码的返回值 responseCode
            int code = httpURLConnection.getResponseCode();
            // 5. 如果返回值正常，数据在网络中是以流的形式得到服务端返回的数据
            String msg = "";
            if (code == 200) { // 正常响应
                log.info("正常响应200码：" +  msg);
                // 从流中读取响应信息
                BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                String line = null;
                while ((line = reader.readLine()) != null) { // 循环从流中读取
                    msg += line;
                }
                reader.close(); // 关闭流
                // 显示响应结果
                log.info("请求返回：" +  msg);
                return msg;
            }else{
                // 显示响应结果
                log.info("异常响应码" + code + "：" +  msg);
                // 从流中读取响应信息
                BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream()));
                String line = null;
                while ((line = reader.readLine()) != null) { // 循环从流中读取
                    msg += line;
                }
                reader.close(); // 关闭流
                // 显示响应结果
                log.info("请求返回：" +  msg);
                return null;
            }
        } catch (Exception e) {
            log.error("请求出错，错误信息："+e.getMessage()+";");
            e.printStackTrace();
            throw e;
        }finally {
            // 6. 断开连接，释放资源
            if (null != httpURLConnection){
                try {
                    httpURLConnection.disconnect();
                }catch (Exception e){
                    log.info("httpURLConnection 流关闭异常："+ e.getLocalizedMessage());
                    e.printStackTrace();
                    throw e;
                }
            }
        }
    }

    public static String httpPost(String getUrl, String body,String contentType) throws Exception{
        HttpURLConnection httpURLConnection = null;
        try {
            // 1. 得到访问地址的URL
            URL url = new URL(getUrl);
            // 2. 得到网络访问对象java.net.HttpURLConnection
            httpURLConnection = (HttpURLConnection) url.openConnection();
            /* 3. 设置请求参数（过期时间，输入、输出流、访问方式），以流的形式进行连接 */
            // 设置是否向HttpURLConnection输出
            httpURLConnection.setDoOutput(true);
            // 设置是否从httpUrlConnection读入
            httpURLConnection.setDoInput(true);
            // 设置请求方式　默认为GET
            httpURLConnection.setRequestMethod("POST");
            // 设置使用标准编码格式编码参数的名-值对
            httpURLConnection.setRequestProperty("Content-Type", contentType);
            // 设置请求头,待选
            //httpURLConnection.addRequestProperty("token","");
            // 设置是否使用缓存
            httpURLConnection.setUseCaches(false);
            // 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向
            httpURLConnection.setInstanceFollowRedirects(true);
            // 设置连接超时时间
            httpURLConnection.setConnectTimeout(3000);
            // 设置读取返回超时时间
            httpURLConnection.setReadTimeout(3000);
            // 连接
            httpURLConnection.connect();

            log.info("请求数据为：" +  body);

            OutputStream out = httpURLConnection.getOutputStream();
            out.write(body.getBytes());
            out.flush();
            out.close();
            // 4. 得到响应状态码的返回值 responseCode
            int code = httpURLConnection.getResponseCode();
            // 5. 如果返回值正常，数据在网络中是以流的形式得到服务端返回的数据
            String msg = "";
            if (code == 200) { // 正常响应
                log.info("正常响应200码：" +  msg);
                // 从流中读取响应信息
                BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                String line = null;
                while ((line = reader.readLine()) != null) { // 循环从流中读取
                    msg += line;
                }
                reader.close(); // 关闭流
                // 显示响应结果
                log.info("请求返回：" +  msg);
                return msg;
            }else{
                // 显示响应结果
                log.info("异常响应码" + code + "：" +  msg);
                // 从流中读取响应信息
                BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream()));
                String line = null;
                while ((line = reader.readLine()) != null) { // 循环从流中读取
                    msg += line;
                }
                reader.close(); // 关闭流
                // 显示响应结果
                log.info("请求返回：" +  msg);
                return null;
            }
        } catch (Exception e) {
            log.error("请求出错，错误信息："+e.getMessage()+";");
            e.printStackTrace();
            throw e;
        }finally {
            // 6. 断开连接，释放资源
            if (null != httpURLConnection){
                try {
                    httpURLConnection.disconnect();
                }catch (Exception e){
                    log.info("httpURLConnection 流关闭异常："+ e.getLocalizedMessage());
                    e.printStackTrace();
                    throw e;
                }
            }
        }
    }

    public static String httpsPost(String getUrl, String body,String contentType) throws Exception{
        HttpsURLConnection httpURLConnection = null;
        try {
            // 1. 得到访问地址的URL
            URL url = new URL(getUrl);
            // 2. 得到网络访问对象java.net.HttpURLConnection
            httpURLConnection = (HttpsURLConnection) url.openConnection();
            /* 3. 设置请求参数（过期时间，输入、输出流、访问方式），以流的形式进行连接 */
            // 设置是否向HttpURLConnection输出
            httpURLConnection.setDoOutput(true);
            // 设置是否从httpUrlConnection读入
            httpURLConnection.setDoInput(true);
            // 设置请求方式　默认为GET
            httpURLConnection.setRequestMethod("POST");
            // 设置使用标准编码格式编码参数的名-值对
            httpURLConnection.setRequestProperty("Content-Type", contentType);
            // 设置请求头,待选
            //httpURLConnection.addRequestProperty("token","");
            // 设置是否使用缓存
            httpURLConnection.setUseCaches(false);
            // 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向
            httpURLConnection.setInstanceFollowRedirects(true);
            // 设置连接超时时间
            httpURLConnection.setConnectTimeout(3000);
            // 设置读取返回超时时间
            httpURLConnection.setReadTimeout(3000);
            // 连接
            httpURLConnection.connect();

            log.info("请求数据为：" +  body);

            OutputStream out = httpURLConnection.getOutputStream();
            out.write(body.getBytes());
            out.flush();
            out.close();
            // 4. 得到响应状态码的返回值 responseCode
            int code = httpURLConnection.getResponseCode();
            // 5. 如果返回值正常，数据在网络中是以流的形式得到服务端返回的数据
            String msg = "";
            if (code == 200) { // 正常响应
                log.info("正常响应200码：" +  msg);
                // 从流中读取响应信息
                BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                String line = null;
                while ((line = reader.readLine()) != null) { // 循环从流中读取
                    msg += line;
                }
                reader.close(); // 关闭流
                // 显示响应结果
                log.info("请求返回：" +  msg);
                return msg;
            }else{
                // 显示响应结果
                log.info("异常响应码" + code + "：" +  msg);
                // 从流中读取响应信息
                BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream()));
                String line = null;
                while ((line = reader.readLine()) != null) { // 循环从流中读取
                    msg += line;
                }
                reader.close(); // 关闭流
                // 显示响应结果
                log.info("请求返回：" +  msg);
                return null;
            }
        } catch (Exception e) {
            log.error("请求出错，错误信息："+e.getMessage()+";");
            e.printStackTrace();
            throw e;
        }finally {
            // 6. 断开连接，释放资源
            if (null != httpURLConnection){
                try {
                    httpURLConnection.disconnect();
                }catch (Exception e){
                    log.info("httpURLConnection 流关闭异常："+ e.getLocalizedMessage());
                    e.printStackTrace();
                    throw e;
                }
            }
        }
    }

    public static String httpsPost(String getUrl, JSONObject body, String contentType) throws Exception{
        HttpsURLConnection httpURLConnection = null;
        try {
            // 1. 得到访问地址的URL
            URL url = new URL(getUrl);
            // 2. 得到网络访问对象java.net.HttpURLConnection
            httpURLConnection = (HttpsURLConnection) url.openConnection();
            /* 3. 设置请求参数（过期时间，输入、输出流、访问方式），以流的形式进行连接 */
            // 设置是否向HttpURLConnection输出
            httpURLConnection.setDoOutput(true);
            // 设置是否从httpUrlConnection读入
            httpURLConnection.setDoInput(true);
            // 设置请求方式　默认为GET
            httpURLConnection.setRequestMethod("POST");
            // 设置使用标准编码格式编码参数的名-值对
            httpURLConnection.setRequestProperty("Content-Type", contentType);
            // 设置请求头,待选
            //httpURLConnection.addRequestProperty("token","");
            // 设置是否使用缓存
            httpURLConnection.setUseCaches(false);
            // 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向
            httpURLConnection.setInstanceFollowRedirects(true);
            // 设置连接超时时间
            httpURLConnection.setConnectTimeout(3000);
            // 设置读取返回超时时间
            httpURLConnection.setReadTimeout(3000);
            // 连接
            httpURLConnection.connect();

            log.info("请求数据为：" +  body);

            OutputStream out = httpURLConnection.getOutputStream();
            out.write(body.toString().getBytes());
            out.flush();
            out.close();
            // 4. 得到响应状态码的返回值 responseCode
            int code = httpURLConnection.getResponseCode();
            // 5. 如果返回值正常，数据在网络中是以流的形式得到服务端返回的数据
            String msg = "";
            if (code == 200) { // 正常响应
                log.info("正常响应200码：" +  msg);
                // 从流中读取响应信息
                BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                String line = null;
                while ((line = reader.readLine()) != null) { // 循环从流中读取
                    msg += line;
                }
                reader.close(); // 关闭流
                // 显示响应结果
                log.info("请求返回：" +  msg);
                return msg;
            }else{
                // 显示响应结果
                log.info("异常响应码" + code + "：" +  msg);
                // 从流中读取响应信息
                BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream()));
                String line = null;
                while ((line = reader.readLine()) != null) { // 循环从流中读取
                    msg += line;
                }
                reader.close(); // 关闭流
                // 显示响应结果
                log.info("请求返回：" +  msg);
                return null;
            }
        } catch (Exception e) {
            log.error("请求出错，错误信息："+e.getMessage()+";");
            e.printStackTrace();
            throw e;
        }finally {
            // 6. 断开连接，释放资源
            if (null != httpURLConnection){
                try {
                    httpURLConnection.disconnect();
                }catch (Exception e){
                    log.info("httpURLConnection 流关闭异常："+ e.getLocalizedMessage());
                    e.printStackTrace();
                    throw e;
                }
            }
        }
    }

    /**
     * 携带证书
     * @param getUrl
     * @param body
     * @param contentType
     * @return
     * @throws Exception
     */
    public static String httpsPostByCA(String getUrl, String body,String contentType ,String caPwd ,String caPath) throws Exception{
        HttpsURLConnection httpURLConnection = null;
        try {
            // 1. 得到访问地址的URL
            URL url = new URL(getUrl);
            // 2. 得到网络访问对象java.net.HttpURLConnection
            httpURLConnection = (HttpsURLConnection) url.openConnection();
            /* 3. 设置请求参数（过期时间，输入、输出流、访问方式），以流的形式进行连接 */
            // 设置是否向HttpURLConnection输出
            httpURLConnection.setDoOutput(true);
            // 设置是否从httpUrlConnection读入
            httpURLConnection.setDoInput(true);
            // 设置请求方式　默认为GET
            httpURLConnection.setRequestMethod("POST");
            // 设置使用标准编码格式编码参数的名-值对
            httpURLConnection.setRequestProperty("Content-Type", contentType);
            // 设置请求头,待选
            //httpURLConnection.addRequestProperty("token","");
            // 设置是否使用缓存
            httpURLConnection.setUseCaches(false);
            // 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向
            httpURLConnection.setInstanceFollowRedirects(true);
            // 设置连接超时时间
            httpURLConnection.setConnectTimeout(3000);
            // 设置读取返回超时时间
            httpURLConnection.setReadTimeout(3000);
            //设置CA证书
            try {
                SSLSocketFactory sslSocketFactory = initCert(caPwd,caPath);
                httpURLConnection.setSSLSocketFactory(sslSocketFactory);
            }catch (Exception e){
                throw new Exception("证书加载错误");
            }
            // 连接
            httpURLConnection.connect();

            log.info("请求数据为：" +  body);

            OutputStream out = httpURLConnection.getOutputStream();
            out.write(body.getBytes());
            out.flush();
            out.close();
            // 4. 得到响应状态码的返回值 responseCode
            int code = httpURLConnection.getResponseCode();
            // 5. 如果返回值正常，数据在网络中是以流的形式得到服务端返回的数据
            String msg = "";
            if (code == 200) { // 正常响应
                log.info("正常响应200码：" +  msg);
                // 从流中读取响应信息
                BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                String line = null;
                while ((line = reader.readLine()) != null) { // 循环从流中读取
                    msg += line;
                }
                reader.close(); // 关闭流
                // 显示响应结果
                log.info("请求返回：" +  msg);
                return msg;
            }else{
                // 显示响应结果
                log.info("异常响应码" + code + "：" +  msg);
                // 从流中读取响应信息
                BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream()));
                String line = null;
                while ((line = reader.readLine()) != null) { // 循环从流中读取
                    msg += line;
                }
                reader.close(); // 关闭流
                // 显示响应结果
                log.info("请求返回：" +  msg);
                return null;
            }
        } catch (Exception e) {
            log.error("请求出错，错误信息："+e.getMessage()+";");
            e.printStackTrace();
            throw e;
        }finally {
            // 6. 断开连接，释放资源
            if (null != httpURLConnection){
                try {
                    httpURLConnection.disconnect();
                }catch (Exception e){
                    log.info("httpURLConnection 流关闭异常："+ e.getLocalizedMessage());
                    e.printStackTrace();
                    throw e;
                }
            }
        }
    }
    
    /**
     * 加载证书
     * @param pwd 证书密码
     * @param path 证书存放地址
     */
    private static SSLSocketFactory initCert(String pwd, String path) throws Exception {
        FileInputStream instream = null;
        try {
            instream = new FileInputStream(new File(path));

            //将证书加载进证书库
            KeyStore ks = KeyStore.getInstance("PKCS12");
            ks.load(instream, pwd.toCharArray());
            //初始化秘钥管理器
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(ks, pwd.toCharArray());

            //信任所有证书
            X509TrustManager tm = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { }

                @Override
                public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                
            };

            SSLContext sslContext = SSLContext.getInstance("TLS");

            // 第一个参数是授权的密钥管理器，用来授权验证。TrustManager[]第二个是被授权的证书管理器，用来验证服务器端的证书。第三个参数是一个随机数值，可以填写null
            sslContext.init(keyManagerFactory.getKeyManagers(), new TrustManager[]{tm}, null);
            return sslContext.getSocketFactory();
        }catch(Exception e){
            e.printStackTrace();
            throw new Exception(e.getMessage());
        }finally {
            if(instream != null){
                try{instream.close();}catch (IOException e1){e1.printStackTrace();}
            }
        }
    }
    public static void main(String[] args) throws Exception{
//        httpGet("http://localhost:8081/test/api/generatortest/list?page=1&limit=10");
//        Map<String,String> map = new HashMap();
//        map.put("name","sss");
//        map.put("age","12");
//        httpPost("http://localhost:8081/test/api/generatortest/save",map);

//        String json = "[1,2]";
//        httpPost("http://localhost:8081/test/api/generatortest/deleteIds",json,JSON);

        new Thread(new Runnable() {

            public void run() {
                for (int i = 0; i < 201; i++) {
                    try {
                        httpGet("http://localhost:8081/test/api/generatortest/all");
                        httpGet("http://localhost:8080/manli/api/generatortest/all");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();


    }


}
